<template>
    <div class="transfer-page">
        <el-container>
            <el-header height="auto">
                <el-card shadow="never">
                    <el-form :inline="true" :model="formInline" label-width="auto" class="filter-form">
                        <el-form-item label="调拨单号">
                            <el-input v-model="formInline.transferNo" clearable placeholder="请输入"
                                style="width: 180px" />
                        </el-form-item>
                        <el-form-item label="单据状态">
                            <el-select v-model="formInline.transferStatus" placeholder="请选择" clearable
                                style="width: 160px">
                                <el-option v-for="status in TRANSFER_STATUS_OPTIONS" :key="status.value"
                                    :label="status.label" :value="status.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="出入库状态">
                            <el-select v-model="formInline.inOutStatus" placeholder="请选择" clearable
                                style="width: 160px">
                                <el-option label="全部" value="" />
                                <el-option label="未出库" value="0" />
                                <el-option label="部分出库" value="1" />
                                <el-option label="已出库" value="2" />
                                <el-option label="未入库" value="3" />
                                <el-option label="部分入库" value="4" />
                                <el-option label="已入库" value="5" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="调拨申请日">
                            <el-date-picker v-model="formInline.dateRange" type="daterange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD"
                                style="width: 260px" clearable />
                        </el-form-item>
                        <el-form-item>
                            <el-space>
                                <el-button type="primary" @click="handleQuery">查询</el-button>
                                <el-button @click="handleReset">重置</el-button>
                                <el-button @click="advancedVisible = true">高级搜索</el-button>
                            </el-space>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-header>

            <el-main>
                <el-card shadow="never">
                    <div class="toolbar">
                        <el-space wrap>
                            <el-button type="success" size="small" @click="handleCreate">新增</el-button>
                            <el-button size="small" @click="handleBatchDelete">删除</el-button>
                            <el-button size="small" @click="handleCopy">复制</el-button>
                            <el-button size="small" @click="handleAudit">审核</el-button>
                            <el-button size="small" @click="handleExport">导出</el-button>
                            <el-button size="small" @click="handleRefresh">刷新</el-button>
                        </el-space>
                    </div>

                    <el-scrollbar x>
                        <el-table ref="multipleTableRef" v-loading="loading" :data="tableData" border stripe
                            style="width: 100%" @selection-change="handleSelectionChange" empty-text="暂无数据">
                            <el-table-column type="selection" width="55" fixed="left" />
                            <el-table-column type="index" label="序号" width="60" fixed="left" />

                            <el-table-column prop="transferNo" label="调拨单号" width="160" fixed="left"
                                show-overflow-tooltip>
                                <template #default="{ row }">
                                    <el-link type="primary" @click="goDetail(row)">
                                        {{ row.transferNo }}
                                    </el-link>
                                </template>
                            </el-table-column>

                            <el-table-column prop="transferStatus" label="单据状态" width="100" fixed="left">
                                <template #default="{ row }">
                                    <el-tag :type="getStatusTagType(row.transferStatus)" size="small">
                                        {{ getStatusText(row.transferStatus) }}
                                    </el-tag>
                                </template>
                            </el-table-column>

                            <el-table-column prop="transferApplicationDate" label="调拨申请日期" width="140">
                                <template #default="{ row }">
                                    {{ formatDate(row.transferApplicationDate) || '-' }}
                                </template>
                            </el-table-column>

                            <el-table-column prop="transferType" label="调拨类型" width="120" show-overflow-tooltip />
                            <el-table-column prop="outboundWarehouseName" label="调出仓库" min-width="140"
                                show-overflow-tooltip />
                            <el-table-column prop="inboundWarehouseName" label="调入仓库" min-width="140"
                                show-overflow-tooltip />

                            <el-table-column prop="outboundStatus" label="出库状态" width="100">
                                <template #default="{ row }">
                                    <el-tag :type="getOutboundStatusTagType(row.outboundStatus)" size="small">
                                        {{ getOutboundStatusText(row.outboundStatus) }}
                                    </el-tag>
                                </template>
                            </el-table-column>

                            <el-table-column prop="inboundStatus" label="入库状态" width="100">
                                <template #default="{ row }">
                                    <el-tag :type="getInboundStatusTagType(row.inboundStatus)" size="small">
                                        {{ getInboundStatusText(row.inboundStatus) }}
                                    </el-tag>
                                </template>
                            </el-table-column>

                            <el-table-column prop="transferQuantity" label="调拨数量" width="100" align="right">
                                <template #default="{ row }">
                                    {{ row.transferQuantity ?? 0 }}
                                </template>
                            </el-table-column>

                            <el-table-column prop="transferAmount" label="调拨金额" width="120" align="right">
                                <template #default="{ row }">
                                    <span class="amount-text">¥{{ Number(row.transferAmount ?? 0).toFixed(2) }}</span>
                                </template>
                            </el-table-column>

                            <el-table-column prop="handler" label="经办人" width="100" show-overflow-tooltip />
                            <el-table-column prop="maker" label="制单人" width="100" show-overflow-tooltip />
                            <el-table-column prop="makerTime" label="制单时间" width="160">
                                <template #default="{ row }">
                                    {{ row.makerTime ? formatDateTime(row.makerTime) : '-' }}
                                </template>
                            </el-table-column>

                            <el-table-column label="操作" fixed="right" width="140" align="center">
                                <template #default="{ row }">
                                    <el-button v-if="canEdit(row)" link type="primary" size="small"
                                        @click="handleEdit(row)">编辑</el-button>
                                    <el-button v-if="canEdit(row)" link type="danger" size="small"
                                        @click="handleDelete(row)">删除</el-button>
                                    <el-button v-if="canRevoke(row)" link type="warning" size="small"
                                        @click="handleRevoke(row)">撤销</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-scrollbar>
                </el-card>

                <el-card shadow="never" class="pagination-card">
                    <div class="pagination-bar">
                        <div class="pagination-info">
                            共{{ page.listCount }}条， 每页{{ page.pagesize }}条， 当前第{{ page.pageindex }}/{{
                                page.pageCount
                            }}页
                        </div>
                        <div class="pagination-controls">
                            <el-button class="pagination-btn" link type="primary" size="small"
                                @click="page.pageindex = 1">
                                首页
                            </el-button>
                            <el-pagination v-model:current-page="page.pageindex" v-model:page-size="page.pagesize"
                                :page-sizes="[10, 20, 50, 100]" :total="page.listCount" prev-text="上一页" next-text="下一页"
                                :background="true" layout="prev, pager, next" />
                            <el-button class="pagination-btn" link type="primary" size="small"
                                @click="page.pageindex = page.pageCount || 1">
                                尾页
                            </el-button>
                            <span class="pagination-jump">
                                前往
                                <el-input-number v-model="page.pageindex" :min="1" :max="page.pageCount || 1"
                                    size="small" controls-position="right" style="width: 90px" />
                                页
                            </span>
                        </div>
                    </div>
                </el-card>
            </el-main>
        </el-container>
    </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, type TableInstance } from 'element-plus'
import moment from 'moment'
import router from '@/router'
import myaxios from '@/http/MyAxios'

interface TransferItem {
    transferId: number
    transferNo: string
    transferStatus: number
    transferApplicationDate: string
    transferType: string
    outboundWarehouseId: number
    outboundWarehouseName: string
    inboundWarehouseId: number
    inboundWarehouseName: string
    outboundStatus: number
    inboundStatus: number
    transferQuantity: number
    transferAmount: number
    handler: string
    maker: string
    makerTime: string
}

const TRANSFER_STATUS_OPTIONS = [
    { value: 0, label: '草稿', tagType: 'info' },
    { value: 1, label: '待审核', tagType: 'warning' },
    { value: 2, label: '驳回', tagType: 'danger' },
    { value: 3, label: '通过', tagType: 'success' },
    { value: 4, label: '已完成', tagType: 'success' },
]

const loading = ref(false)
const tableData = ref<TransferItem[]>([])
const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<TransferItem[]>([])
const advancedVisible = ref(false)

const formInline = reactive({
    transferNo: '',
    transferStatus: '',
    inOutStatus: '',
    dateRange: [] as string[],
})

const page = reactive({
    pageindex: 1,
    pagesize: 10,
    listCount: 0,
    pageCount: 0,
})

const normalizeTransferRecord = (item: any): TransferItem => {
    return {
        transferId: Number(item.transferId ?? item.id ?? 0),
        transferNo: item.transferNo || item.transferNumber || '',
        transferStatus: Number(item.documentStatus ?? item.transferStatus ?? item.status ?? 0),
        transferApplicationDate: item.transferApplicationDate || item.transferApplyDate || item.applyDate || '',
        transferType: item.transferType || item.transferTypeName || '',
        outboundWarehouseId: Number(item.outWarehouseId ?? item.outboundWarehouseId ?? 0),
        outboundWarehouseName: item.outWarehouseName || item.outboundWarehouseName || '',
        inboundWarehouseId: Number(item.inWarehouseId ?? item.inboundWarehouseId ?? 0),
        inboundWarehouseName: item.inWarehouseName || item.inboundWarehouseName || '',
        outboundStatus: Number(item.outboundStatus ?? item.outStatus ?? item.outStatusValue ?? 0),
        inboundStatus: Number(item.inboundStatus ?? item.inStatus ?? item.inStatusValue ?? 0),
        transferQuantity: Number(item.transferQuantity ?? item.quantity ?? item.totalQty ?? 0),
        transferAmount: Number(item.transferAmount ?? item.amount ?? item.totalAmount ?? 0),
        handler: item.handler || item.handlerName || item.handleMan || '',
        maker: item.maker || item.makerName || item.createdBy || item.creator || '',
        makerTime: item.makerTime || item.createTime || item.createdTime || '',
    }
}

const fetchData = () => {
    loading.value = true
    myaxios
        .get('/api/Transfer/GetTransferPage', {
            params: {
                transferNo: formInline.transferNo,
                transferStatus: formInline.transferStatus,
                inOutStatus: formInline.inOutStatus,
                beginDate: formInline.dateRange?.[0] || '',
                endDate: formInline.dateRange?.[1] || '',
                pageindex: page.pageindex,
                pagesize: page.pagesize,
            },
        })
        .then((res) => {
            const result = res.data || {}
            if (result.code === 200) {
                const rawList =
                    (Array.isArray(result.data?.data) ? result.data?.data : result.data?.data?.data) || []
                tableData.value = rawList.map((item: any) => normalizeTransferRecord(item))
                page.listCount = result.data?.listCount ?? result.data?.data?.listCount ?? rawList.length ?? 0
                page.pageCount = result.data?.pageCount ?? result.data?.data?.pageCount ?? 0
            } else {
                ElMessage.error(result.message || '获取调拨列表失败')
            }
        })
        .catch((err) => {
            console.error('获取调拨列表失败:', err)
            ElMessage.error('获取调拨列表失败')
        })
        .finally(() => {
            loading.value = false
        })
}

onMounted(() => {
    fetchData()
})

watch(
    () => [page.pageindex, page.pagesize],
    () => {
        fetchData()
    },
)

const handleQuery = () => {
    page.pageindex = 1
    fetchData()
}

const handleReset = () => {
    formInline.transferNo = ''
    formInline.transferStatus = ''
    formInline.inOutStatus = ''
    formInline.dateRange = []
    page.pageindex = 1
    fetchData()
}

const handleSelectionChange = (val: TransferItem[]) => {
    multipleSelection.value = val
}

const handleCreate = () => {
    router.push('/CreateTransfer')
}

const TRANSFER_DETAIL_CACHE_KEY = 'TRANSFER_DETAIL_CACHE'

const goDetail = (row: TransferItem) => {
    sessionStorage.setItem(TRANSFER_DETAIL_CACHE_KEY, JSON.stringify(row))
    router.push({
        path: '/DetailTransfer',
        query: { transferId: row.transferId },
    })
}

const TRANSFER_EDIT_CACHE_KEY = 'TRANSFER_EDIT_CACHE'

const handleEdit = (row: TransferItem) => {
    sessionStorage.setItem(TRANSFER_EDIT_CACHE_KEY, JSON.stringify(row))
    router.push({
        path: '/UpdateTransfer',
        query: { transferId: row.transferId },
    })
}

const handleDelete = (row: TransferItem) => {
    ElMessageBox.confirm('确认删除该调拨单吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            myaxios
                .delete('/api/Transfer/DeleteTransfer', {
                    params: { transferId: row.transferId },
                })
                .then((res) => {
                    if (res.data?.code === 200) {
                        ElMessage.success('删除成功')
                        fetchData()
                    } else {
                        ElMessage.error(res.data?.message || '删除失败')
                    }
                })
                .catch((err) => {
                    console.error('删除失败:', err)
                    ElMessage.error('删除失败')
                })
        })
        .catch(() => { })
}

const handleBatchDelete = () => {
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请选择要删除的数据')
        return
    }
    ElMessageBox.confirm(`确认删除选中的 ${multipleSelection.value.length} 条数据吗？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            const deletePromises = multipleSelection.value.map((row) =>
                myaxios.delete('/api/Transfer/DeleteTransfer', {
                    params: { transferId: row.transferId },
                })
            )
            Promise.all(deletePromises)
                .then(() => {
                    ElMessage.success('批量删除成功')
                    multipleSelection.value = []
                    fetchData()
                })
                .catch((err) => {
                    console.error('批量删除失败:', err)
                    ElMessage.error('批量删除失败')
                })
        })
        .catch(() => { })
}

const handleCopy = () => {
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请选择要复制的数据')
        return
    }
    if (multipleSelection.value.length > 1) {
        ElMessage.warning('一次只能复制一条数据')
        return
    }
    const row = multipleSelection.value[0]
    if (!row) return
    router.push({
        path: '/CreateTransfer',
        query: { copyFrom: row.transferId },
    })
}

const handleAudit = () => {
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请选择要审核的数据')
        return
    }
    ElMessage.info('审核功能待实现')
}

const handleExport = () => {
    ElMessage.info('导出功能待实现')
}

const handleRefresh = () => {
    fetchData()
}

const handleRevoke = (row: TransferItem) => {
    ElMessageBox.confirm('确认撤销该调拨单吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            ElMessage.info('撤销功能待实现')
        })
        .catch(() => { })
}

const canEdit = (row: TransferItem) => {
    return row.transferStatus === 0 || row.transferStatus === 1 || row.transferStatus === 2
}

const canRevoke = (row: TransferItem) => {
    return row.transferStatus === 3 || row.transferStatus === 4
}

const getStatusText = (status?: number) => {
    const option = TRANSFER_STATUS_OPTIONS.find((opt) => opt.value === status)
    return option?.label || '——'
}

const getStatusTagType = (status?: number) => {
    const option = TRANSFER_STATUS_OPTIONS.find((opt) => opt.value === status)
    return option?.tagType || 'info'
}

const getOutboundStatusText = (status?: number) => {
    switch (status) {
        case 0:
            return '未出库'
        case 1:
            return '部分出库'
        case 2:
            return '已出库'
        default:
            return '——'
    }
}

const getOutboundStatusTagType = (status?: number) => {
    switch (status) {
        case 0:
            return 'info'
        case 1:
            return 'warning'
        case 2:
            return 'success'
        default:
            return 'info'
    }
}

const getInboundStatusText = (status?: number) => {
    switch (status) {
        case 0:
            return '未入库'
        case 1:
            return '部分入库'
        case 2:
            return '已入库'
        default:
            return '——'
    }
}

const getInboundStatusTagType = (status?: number) => {
    switch (status) {
        case 0:
            return 'info'
        case 1:
            return 'warning'
        case 2:
            return 'success'
        default:
            return 'info'
    }
}

const formatDate = (date?: string) => {
    if (!date) return '-'
    return moment(date).format('YYYY-MM-DD')
}

const formatDateTime = (date?: string) => {
    if (!date) return '-'
    return moment(date).format('YYYY-MM-DD HH:mm:ss')
}
</script>

<style scoped>
.transfer-page {
    padding: 20px;
}

.filter-form {
    margin-top: 0;
}

.toolbar {
    margin-bottom: 12px;
}

.pagination-card {
    margin-top: 16px;
}

.pagination-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.pagination-info {
    color: #606266;
    font-size: 14px;
}

.pagination-controls {
    display: flex;
    align-items: center;
    gap: 8px;
}

.pagination-btn {
    margin: 0 4px;
}

.pagination-jump {
    margin-left: 16px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.amount-text {
    color: #ff5722;
    font-weight: 600;
}
</style>
